package com.hp.mvc.controller;

import com.hp.mvc.pojo.Book;
import com.hp.mvc.pojo.JsonResult;
import com.hp.mvc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class BookController {

    //注入Service对象
    @Autowired
    private BookService bookService;

    @GetMapping("/books")
    public JsonResult findAll(){
        try{
            return new JsonResult(1,"ok",bookService.findAll());
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @GetMapping("/book/{id}")
    public JsonResult findById(@PathVariable("id")Long id){
        try{
            return new JsonResult(1,"ok",bookService.findById(id));
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    //name=xx&age=20
    @PostMapping("/book")
    public JsonResult addBook(Book book){
        try{
            bookService.add(book);
            return new JsonResult(1,"ok",book);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @PutMapping("/book")
    public JsonResult updateBook(Book book){
        try{
            bookService.update(book);
            return new JsonResult(1,"ok",book);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @DeleteMapping("/book/{id}")
    public JsonResult deleteById(@PathVariable("id")Long id){
        try{
            bookService.delete(id);
            return new JsonResult(1,"ok",bookService.findAll());
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }
}
